﻿/*
* Copyright 2009-2010 AKABANA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
using System.IO;

using Akabana.Amf.IO;

namespace Akabana.Amf.Amf3.IO
{
    public static class Amf3WriterExt
    {
        public static void WriteS29(this AmfWriter writer, int value)
        {
            if (value < 0)
            {
                writer.Write((byte)(((value >> 22) & 0x7f) | 0xC0));
                writer.Write((byte)(((value >> 15) & 0x7f) | 0x80));
                writer.Write((byte)(((value >> 8) & 0x7f) | 0x80));
                writer.Write((byte)(value & 0xff));
            }
            else
            {
                writer.WriteU29(value);
            }
        }

        public static void WriteU29(this BinaryWriter writer, int value)
        {
            if (value < 0x80)
            {
                writer.Write((byte)value);
            }
            else if (value < 0x4000)
            {
                writer.Write((byte)(((value >> 7) & 0x7f) | 0x80));
                writer.Write((byte)(value & 0x7f));
            }
            else if (value < 0x200000)
            {
                writer.Write((byte)(((value >> 14) & 0x7f) | 0x80));
                writer.Write((byte)(((value >> 7) & 0x7f) | 0x80));
                writer.Write((byte)(value & 0x7f));

            }
            else if (value < 0x10000000)
            {
                writer.Write((byte)(((value >> 22) & 0x7f) | 0x80));
                writer.Write((byte)(((value >> 15) & 0x7f) | 0x80));
                writer.Write((byte)(((value >> 8) & 0x7f) | 0x80));
                writer.Write((byte)(value & 0xff));
            }
        }

        public static void WriteTypeMarker(this BinaryWriter writer, Amf3TypeMarker value)
        {
            writer.Write((byte)value);
        }
    }
}
